package org.belkodevelop.mail;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class SimpleMailSender extends JavaMailSenderImpl {
    
    private static final String TEMPLATE_EXT = "html";
    private static final String ENCODING = "UTF-8";
    
    private VelocityEngine velocityEngine;
    
    private TaskExecutor taskExecutor;
    
    private String pathMailTemplate; 
    
    private String siteUrl;
    
    @Autowired
    public SimpleMailSender(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }    
    
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }    
    
    public void setPathMailTemplate(String path) {
        this.pathMailTemplate = path;
    }
    
    public void setSiteUrl(String siteUrl) {
        this.siteUrl = siteUrl;
    }
  
    public void send(final Mail mail) throws MailException {
        taskExecutor.execute(new AsyncMailTask(mail));
    }
    
    private final class AsyncMailTask implements Runnable {
 
        private final Mail mail;
 
        private AsyncMailTask(final Mail mail) {
            this.mail = mail;
        }
 
        @Override
        public void run() {
            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                @Override
                public void prepare(MimeMessage mimeMessage) throws MessagingException, UnsupportedEncodingException {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, ENCODING);
                    message.setTo(mail.getTo());
                    Person person = mail.getTemplate().getPerson();
                    if (person != null) {
                        if (person.getEmail() != null && person.getName() != null) {
                            message.setFrom(person.getEmail(), person.getName()); 
                        }
                        else if (person.getEmail() != null) {
                            message.setFrom(person.getEmail()); 
                        }
                    }
                    message.setSubject(mail.getTemplate().getSubject());
                    Map<String, Object> model = new HashMap<>(mail.getModel());
                    model.put("siteUrl", siteUrl);
                    String text = VelocityEngineUtils.mergeTemplateIntoString(
                        velocityEngine, pathMailTemplate + mail.getTemplate().getTemplateName() + "." + 
                        TEMPLATE_EXT, ENCODING, model);
                    message.setText(text, true);
                }
            };
            SimpleMailSender.this.send(preparator);            
        }
    }
    
}
